<template>
  <el-card class="user-profile-card" shadow="hover" :body-style="{ padding: '20px' }">
    <!-- 卡片头部：头像和基本信息 -->
    <div class="card-header">
      <div class="avatar-section">
        <!-- 增强版头像上传功能 -->
        <el-upload
            v-if="enableUpload"
            class="avatar-uploader"
            action="/api/upload/avatar"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            accept="image/jpeg,image/png,image/gif"
        >
          <el-avatar
              :size="80"
              :src="displayAvatar"
              :alt="user.username + '的头像'"
              class="user-avatar"
              @error="handleAvatarLoadError"
          >
            <span class="avatar-fallback">{{ user.username?.charAt(0) || 'U' }}</span>
          </el-avatar>
          <div class="upload-overlay" v-if="enableUpload">
            <el-icon><Camera /></el-icon>
          </div>
        </el-upload>

        <el-avatar
            v-else
            :size="80"
            :src="displayAvatar"
            :alt="user.username + '的头像'"
            class="user-avatar"
            @error="handleAvatarLoadError"
        >
          <span class="avatar-fallback">{{ user.username?.charAt(0) || 'U' }}</span>
        </el-avatar>

        <div class="verify-badge" v-if="user.verified" :title="user.verifiedText || '已认证'">
          <el-icon color="#00a1d6"><Select /></el-icon>
        </div>

        <!-- 在线状态指示器 -->
        <div v-if="showOnlineStatus" class="online-status" :class="{ online: user.isOnline }"
             :title="user.isOnline ? '在线' : '离线'">
        </div>
      </div>

      <div class="basic-info">
        <div class="username-section">
          <h3 class="username" :title="user.username">{{ user.username }}</h3>
          <el-tag
              v-if="user.vipLevel"
              size="small"
              effect="dark"
              type="warning"
              class="vip-tag"
          >
            LV{{ user.vipLevel }}
          </el-tag>
          <!-- 性别标识 -->
          <el-tag
              v-if="user.gender"
              size="small"
              :type="user.sex === 'male' ? 'primary' : 'danger'"
              class="gender-tag"
          >
            <el-icon><Male v-if="user.sex === 'male'" /><Female v-else /></el-icon>
            {{ user.sex === 'male' ? '男' : '女' }}
          </el-tag>
        </div>

        <p class="signature" :title="user.description || '暂无签名'">
          {{ user.description || '这个人很懒，什么都没有写～' }}
        </p>

        <!-- 等级进度条 -->
        <div v-if="showLevelProgress" class="level-progress">
          <div class="progress-info">
            <span>Lv.{{ user.level || 1 }}</span>
            <span>经验 {{ user.currentExp || 0 }}/{{ user.nextLevelExp || 100 }}</span>
          </div>
          <el-progress
              :percentage="calculateLevelProgress()"
              :show-text="false"
              stroke-width="6"
              color="#00a1d6"
          />
        </div>

        <el-button
            v-if="showEditButton"
            type="primary"
            size="small"
            class="edit-btn"
            @click="handleEdit"
            :loading="editLoading"
        >
          <el-icon><Edit /></el-icon>
          {{ editLoading ? '编辑中...' : '编辑资料' }}
        </el-button>
      </div>
    </div>

    <!-- 统计数据 -->
    <el-row :gutter="16" class="stats-section">
      <el-col :span="8" class="stat-item" @click="handleStatClick('dynamic')">
        <div class="stat-number">{{ formatCount(user.stats.dynamic) }}</div>
        <div class="stat-label">动态</div>
      </el-col>
      <el-col :span="8" class="stat-item" @click="handleStatClick('following')">
        <div class="stat-number">{{ formatCount(user.stats.following) }}</div>
        <div class="stat-label">关注</div>
      </el-col>
      <el-col :span="8" class="stat-item" @click="handleStatClick('followers')">
        <div class="stat-number">{{ formatCount(user.stats.followers) }}</div>
        <div class="stat-label">粉丝</div>
      </el-col>
    </el-row>

    <!-- 附加信息 -->
    <div class="additional-info" v-if="showAdditionalInfo && hasAdditionalInfo">
      <div class="info-item" v-if="user.location">
        <el-icon><Location /></el-icon>
        <span>{{ user.location }}</span>
      </div>
      <div class="info-item" v-if="user.joinDate">
        <el-icon><Calendar /></el-icon>
        <span>加入于 {{ formatJoinDate(user.joinDate) }}</span>
      </div>
      <div class="info-item" v-if="user.email && showEmail">
        <el-icon><Message /></el-icon>
        <span>{{ user.email }}</span>
      </div>
      <!-- 扩展信息字段 -->
      <div class="info-item" v-if="user.industry">
        <el-icon><Briefcase /></el-icon>
        <span>{{ user.industry }}</span>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button
          type="primary"
          class="follow-btn"
          :loading="followLoading"
          @click="handleFollow"
          :icon="user.isFollowing ? Check : Plus"
      >
        {{ user.isFollowing ? '已关注' : '关注' }}
      </el-button>
      <el-button
          class="message-btn"
          @click="handleMessage"
          :disabled="!user.isFollowing && !allowMessageStrangers"
      >
        <el-icon><ChatDotRound /></el-icon>
        私信
      </el-button>
      <!-- 更多操作下拉菜单 -->
      <el-dropdown @command="handleMoreCommand" class="more-dropdown">
        <el-button class="more-btn">
          <el-icon><More /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="share" :icon="Share">分享名片</el-dropdown-item>
            <el-dropdown-item command="report" :icon="Warning">举报</el-dropdown-item>
            <el-dropdown-item
                v-if="user.isBlocked"
                command="unblock"
                :icon="Unlock"
            >
              取消屏蔽
            </el-dropdown-item>
            <el-dropdown-item
                v-else
                command="block"
                :icon="Lock"
                divided
            >
              屏蔽
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 骨架屏加载状态 -->
    <div v-if="loading" class="skeleton-loading">
      <el-skeleton animated>
        <template #template>
          <div class="skeleton-header">
            <el-skeleton-item variant="circle" size="80" />
            <div class="skeleton-info">
              <el-skeleton-item variant="h3" width="60%" />
              <el-skeleton-item variant="text" width="80%" />
              <el-skeleton-item variant="button" width="40%" />
            </div>
          </div>
          <div class="skeleton-stats">
            <el-skeleton-item variant="text" width="30%" />
            <el-skeleton-item variant="text" width="30%" />
            <el-skeleton-item variant="text" width="30%" />
          </div>
        </template>
      </el-skeleton>
    </div>
  </el-card>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Edit,
  Select,
  Location,
  Calendar,
  ChatDotRound,
  Camera,
  Message,
  Briefcase,
  Check,
  Plus,
  More,
  Share,
  Warning,
  Lock,
  Unlock,
  Male,
  Female
} from '@element-plus/icons-vue'

// Props定义 - 增强参数配置
const props = defineProps({
  user: {
    type: Object,
    required: true,
    default: () => ({
      username: '用户名',
      avatar: '',
      description: '',
      verified: false,
      verifiedText: '',
      vipLevel: 0,
      level: 1,
      currentExp: 0,
      nextLevelExp: 100,
      sex: '',
      isOnline: false,
      stats: {
        dynamic: 0,
        following: 0,
        followers: 0
      },
      location: '',
      joinDate: '',
      email: '',
      industry: '',
      isFollowing: false,
      isBlocked: false
    })
  },
  showAdditionalInfo: {
    type: Boolean,
    default: true
  },
  showEditButton: {
    type: Boolean,
    default: true
  },
  enableUpload: {
    type: Boolean,
    default: false
  },
  showOnlineStatus: {
    type: Boolean,
    default: true
  },
  showLevelProgress: {
    type: Boolean,
    default: false
  },
  showEmail: {
    type: Boolean,
    default: false
  },
  allowMessageStrangers: {
    type: Boolean,
    default: false
  },
  loading: {
    type: Boolean,
    default: false
  }
})

// Emits定义 - 扩展事件
const emit = defineEmits([
  'edit',
  'follow',
  'message',
  'avatar-uploaded',
  'stat-click',
  'more-command',
  'update:user'
])

// 响应式数据
const followLoading = ref(false)
const editLoading = ref(false)
const uploadLoading = ref(false)

// 计算属性
const displayAvatar = computed(() => {
  return props.user.avatar || generateDefaultAvatar(props.user.username)
})

const hasAdditionalInfo = computed(() => {
  return props.user.location || props.user.joinDate || props.user.email || props.user.industry
})

// 处理方法
const handleAvatarLoadError = (event) => {
  console.warn('头像加载失败，使用默认头像:', event)
  // 可以触发默认头像生成
}

const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }

  uploadLoading.value = true
  return true
}

const handleAvatarSuccess = (response) => {
  uploadLoading.value = false
  ElMessage.success('头像上传成功')
  emit('avatar-uploaded', response.url)
  // 更新本地头像显示
  emit('update:user', {
    ...props.user,
    avatar: response.url
  })
}

const handleAvatarError = (error) => {
  uploadLoading.value = false
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败，请重试')
}

const handleEdit = () => {
  editLoading.value = true
  emit('edit', props.user)
  // 模拟编辑完成
  setTimeout(() => {
    editLoading.value = false
  }, 1000)
}

const handleFollow = async () => {
  if (followLoading.value) return

  followLoading.value = true
  try {
    // 添加确认对话框
    if (!props.user.isFollowing) {
      await ElMessageBox.confirm(
          `确定要关注 ${props.user.username} 吗？`,
          '关注确认',
          { type: 'info' }
      )
    }

    await new Promise(resolve => setTimeout(resolve, 800))
    emit('follow', {
      userId: props.user.id,
      follow: !props.user.isFollowing
    })

    ElMessage.success(props.user.isFollowing ? '取消关注成功' : '关注成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    followLoading.value = false
  }
}

const handleMessage = () => {
  if (!props.user.isFollowing && !props.allowMessageStrangers) {
    ElMessage.warning('请先关注该用户才能发送私信')
    return
  }
  emit('message', props.user)
}

const handleStatClick = (statType) => {
  emit('stat-click', {
    type: statType,
    value: props.user.stats[statType],
    user: props.user
  })
}

const handleMoreCommand = (command) => {
  emit('more-command', {
    command,
    user: props.user
  })

  switch (command) {
    case 'share':
      ElMessage.info('分享功能开发中')
      break
    case 'report':
      handleReport()
      break
    case 'block':
      handleBlock()
      break
    case 'unblock':
      handleUnblock()
      break
  }
}

const handleReport = async () => {
  try {
    await ElMessageBox.prompt('请输入举报原因', '举报用户', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '请输入举报原因'
    })
    ElMessage.success('举报提交成功，我们将尽快处理')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('举报失败:', error)
    }
  }
}

const handleBlock = async () => {
  try {
    await ElMessageBox.confirm(
        `确定要屏蔽 ${props.user.username} 吗？屏蔽后将不再看到该用户的内容`,
        '屏蔽确认',
        { type: 'warning' }
    )
    ElMessage.success('用户已屏蔽')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
    }
  }
}

const handleUnblock = async () => {
  try {
    await ElMessageBox.confirm(
        `确定要取消屏蔽 ${props.user.username} 吗？`,
        '取消屏蔽确认',
        { type: 'info' }
    )
    ElMessage.success('已取消屏蔽')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
    }
  }
}

// 工具函数
const formatCount = (count) => {
  const num = count || 0
  if (num >= 100000000) {
    return (num / 100000000).toFixed(1) + '亿'
  } else if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + '千'
  }
  return num.toString()
}

const formatJoinDate = (dateString) => {
  if (!dateString) return '未知时间'
  try {
    const date = new Date(dateString)
    const now = new Date()
    const diffTime = Math.abs(now - date)
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

    if (diffDays <= 7) {
      return `${diffDays}天前`
    } else if (diffDays <= 30) {
      return `${Math.floor(diffDays / 7)}周前`
    } else {
      return date.getFullYear() + '年' + (date.getMonth() + 1) + '月'
    }
  } catch {
    return dateString
  }
}

const calculateLevelProgress = () => {
  const current = props.user.currentExp || 0
  const next = props.user.nextLevelExp || 100
  return Math.min(Math.round((current / next) * 100), 100)
}

const generateDefaultAvatar = (username) => {
  // 根据用户名生成默认头像颜色
  const colors = ['#00a1d6', '#f56a00', '#7265e6', '#ffbf00', '#00c4cc']
  const index = username.length % colors.length
  return `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="80" height="80"><rect width="80" height="80" fill="${colors[index]}"/><text x="40" y="45" text-anchor="middle" fill="white" font-size="24">${username.charAt(0)}</text></svg>`
}

// 监听用户数据变化
watch(() => props.user, (newVal) => {
  console.log('用户数据更新:', newVal)
}, { deep: true })

// 暴露方法供父组件调用
defineExpose({
  refresh: () => {
    console.log('刷新用户数据')
  },
  startLoading: () => {
    editLoading.value = true
  },
  stopLoading: () => {
    editLoading.value = false
    followLoading.value = false
  }
})
</script>

<style scoped>
.user-profile-card {
  max-width: 400px;
  margin: 0 auto;
  border-radius: 12px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.user-profile-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  margin-bottom: 20px;
}

.avatar-section {
  position: relative;
  flex-shrink: 0;
}

.user-avatar {
  border: 3px solid #f0f0f0;
  transition: all 0.3s ease;
  cursor: pointer;
}

.user-avatar:hover {
  border-color: #00a1d6;
  transform: scale(1.05);
}

.avatar-uploader {
  position: relative;
  display: inline-block;
}

.upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-uploader:hover .upload-overlay {
  opacity: 1;
}

.avatar-fallback {
  font-size: 24px;
  font-weight: bold;
  color: #fff;
  background: linear-gradient(135deg, #00a1d6, #00c4cc);
}

.verify-badge {
  position: absolute;
  bottom: 2px;
  right: 2px;
  width: 20px;
  height: 20px;
  background: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 2;
}

.online-status {
  position: absolute;
  top: 2px;
  right: 2px;
  width: 12px;
  height: 12px;
  border: 2px solid white;
  border-radius: 50%;
  background: #ccc;
  z-index: 2;
}

.online-status.online {
  background: #52c41a;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.basic-info {
  flex: 1;
  min-width: 0;
}

.username-section {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.username {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #18191c;
  line-height: 1.2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.vip-tag, .gender-tag {
  font-size: 12px;
  padding: 2px 6px;
  flex-shrink: 0;
}

.signature {
  margin: 8px 0 12px 0;
  font-size: 14px;
  color: #61666d;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  min-height: 1.4em;
}

.level-progress {
  margin: 12px 0;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.edit-btn {
  margin-top: 8px;
}

.stats-section {
  margin: 20px 0;
  padding: 16px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 4px;
  border-radius: 4px;
}

.stat-item:hover {
  background: #f5f7fa;
  transform: translateY(-1px);
}

.stat-number {
  font-size: 18px;
  font-weight: 600;
  color: #00a1d6;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #999;
}

.additional-info {
  margin: 16px 0;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #61666d;
}

.info-item .el-icon {
  color: #999;
  width: 14px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  margin-top: 16px;
}

.follow-btn, .message-btn, .more-btn {
  flex: 1;
}

.more-dropdown {
  flex: 0 0 auto;
}

.follow-btn {
  background: linear-gradient(135deg, #00a1d6, #00c4cc);
  border: none;
}

.follow-btn:hover:not(:disabled) {
  opacity: 0.9;
  transform: translateY(-1px);
}

.message-btn:hover:not(:disabled) {
  border-color: #00a1d6;
  color: #00a1d6;
}

.more-btn {
  width: 40px;
  min-width: 40px;
}

.skeleton-loading {
  padding: 20px;
}

.skeleton-header {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.skeleton-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.skeleton-stats {
  display: flex;
  justify-content: space-around;
  padding: 16px 0;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .user-profile-card {
    margin: 0 12px;
    max-width: none;
  }

  .card-header {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }

  .username-section {
    justify-content: center;
  }

  .action-buttons {
    flex-direction: row;
  }

  .stats-section {
    margin: 16px 0;
    padding: 12px 0;
  }

  .stat-number {
    font-size: 16px;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .user-profile-card {
    background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
    color: #ffffff;
  }

  .username {
    color: #ffffff;
  }

  .signature {
    color: #aaaaaa;
  }

  .stat-item:hover {
    background: #2a2a2a;
  }
}
</style>